package com.hrpc.compress;

import com.hrpc.compress.impl.GzipCompressorImpl;
import com.hrpc.config.ObjectWrapper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CompressorFactory {
    private final static Map<String, ObjectWrapper<Compressor>> COMPRESSOR_CACHE =new ConcurrentHashMap<>(8);
    private final static Map<Byte,ObjectWrapper<Compressor>> COMPRESSOR_CACHE_CODE =new ConcurrentHashMap<>(8);

    static {
        ObjectWrapper<Compressor> gzip = new ObjectWrapper<>((byte) 1, "zip", new GzipCompressorImpl());
        COMPRESSOR_CACHE.put("gzip",gzip);
        COMPRESSOR_CACHE_CODE.put((byte) 1,gzip);
    }

    /**
     * 使用工厂方法获取一个compressorWrapper
     * @param
     * @return
     */
    public static ObjectWrapper<Compressor> getCompressor(String compressorType) {
        ObjectWrapper<Compressor> compressorWrapper = COMPRESSOR_CACHE.get(compressorType);
        if (compressorWrapper == null){
            return COMPRESSOR_CACHE.get("gzip");
        }
        return compressorWrapper;
    }
    public static ObjectWrapper<Compressor> getCompressor(byte compressorCode) {
        ObjectWrapper<Compressor> compressorWrapper = COMPRESSOR_CACHE_CODE.get(compressorCode);
        if (compressorWrapper == null){
            return COMPRESSOR_CACHE.get("gzip");
        }
        return COMPRESSOR_CACHE_CODE.get(compressorCode);
    }

    /**
     * 给工厂中新增一个压缩方式
     * @param objectWrapper 压缩类型的包装
     */
    public static void addCompressor(ObjectWrapper<Compressor> objectWrapper){
        COMPRESSOR_CACHE.put(objectWrapper.getName(),objectWrapper);
        COMPRESSOR_CACHE_CODE.put(objectWrapper.getCode(), objectWrapper);
    }

}
